package com.car.carsharing.service.impl;

import com.car.carsharing.dto.CouponDTO;
import com.car.carsharing.dto.TableListDto;
import com.car.carsharing.mapper.CouponMapper;
import com.car.carsharing.pojo.Coupon;
import com.car.carsharing.service.CouponService;
import com.car.carsharing.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CouponServiceImpl implements CouponService {
    @Autowired
    private CouponMapper couponMapper;
    @Override
    public TableListDto getCoupon(Map map) {

        Integer pageSize = (Integer) map.get("pageSize");

        if(pageSize == null || "".equals(pageSize)){
            pageSize = 10;
        }
        Integer pageNum = (Integer) map.get("pageNum");
        if(pageNum == null || "".equals(pageNum)){
            pageNum = 1;
        }

        Coupon coupon = new Coupon();
        coupon.setTitle((String) map.get("title"));

        PageHelper.startPage(pageNum,pageSize);
        List<Coupon> coupon1 = couponMapper.getCoupon(coupon);
        PageInfo pageInfo = new PageInfo(coupon1);
        return new TableListDto().sucess(coupon1,"查询成功",pageInfo.getTotal());
    }

    @Override
    public List<CouponDTO> getUserCouponById(Integer userId) {
        List<CouponDTO> coupons = couponMapper.getUserCouponById(userId);

        if( coupons == null || coupons.size() == 0 ){
            return null;
        }

        for (CouponDTO coupon : coupons) {

            if(StringUtils.isDateTime(coupon.getEffectiveTime())){
                if(StringUtils.effectiveTime(StringUtils.getTime(new Date()),coupon.getEffectiveTime()) <0){
                    coupon.setEffectiveTime("有效时间至："+coupon.getEffectiveTime());
                    coupon.setEffective(false);
                }else{
                    coupon.setEffective(true);
                                }
            }else{
                Integer count = Integer.parseInt(coupon.getEffectiveTime());
                if(count<=0){
                    coupon.setEffective(true);

                }else{
                    coupon.setEffectiveTime("有效次数："+coupon.getEffectiveTime());
                    coupon.setEffective(false);
                }
            }


        }
        return coupons;
    }

    @Override
    public int updateCoupon(Coupon coupon) {
        return couponMapper.updateCoupon(coupon);
    }

    @Override
    public int addCoupon(Coupon coupon) {
        return couponMapper.addCoupon(coupon);
    }

    @Override
    public List<CouponDTO> getCouponNum() {
        return couponMapper.getCouponNum();
    }
}
